package com.woniu.consumer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.mapper.GoodsMapper;
import com.woniu.mapper.GoodsOrderMapper;
import com.woniu.mapper.OrderDetailsMapper;
import com.woniu.model.Goods;
import com.woniu.model.GoodsOrder;
import com.woniu.model.OrderDetails;
import com.woniu.utils.StateData;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.util.List;

//消费者
@Component
@RabbitListener(queues = "points_order_queue")
public class OrderNumQueueConsumer {
    @Resource
    private GoodsOrderMapper goodsOrderMapper;
    @Resource
    private OrderDetailsMapper orderDetailsMapper;

    @Resource
    private GoodsMapper goodsMapper;
    @GlobalTransactional(rollbackFor = Throwable.class)
    @RabbitHandler
    public void checkOrder(String orderNum)  {
        //用户未对订单付款 取消订单 还原库存
        GoodsOrder goodsOrder = goodsOrderMapper.selectById(orderNum);
        goodsOrder.setState(Long.valueOf(StateData.ORDER_STATE_CANCEL));
        goodsOrderMapper.updateById(goodsOrder);
        List<OrderDetails> list = orderDetailsMapper.selectList(new QueryWrapper<OrderDetails>().eq("order_id", orderNum));
        for (OrderDetails item : list) {
            Goods bookInfo = goodsMapper.selectById(item.getGoodsId());
            bookInfo.setNumber((int) (bookInfo.getNumber()+item.getGoodsCont()));
            bookInfo.setFreeze((int) (bookInfo.getFreeze()- item.getGoodsCont()));
            goodsMapper.updateById(bookInfo);
        }


    }
}
